import { routerRedux } from 'dva/router';
import { submit } from '@/services/commonService';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { sysName } from '@/common/sysParam';
import { isEmptyObject, showSuccess, showError, print } from '@/utils/sysFun';
import { getStorageBykey, saveStorage } from '@/utils/storage';
import api from '../common/api';
// import sm3 from '@/utils/sm3-babel';

export default {
  namespace: 'global',

  state: {
    collapsed: false,
    currentUser: {},
    status: false,
  },

  effects: {
    *fetchCurrent(_, { select, put }) {
      if (document.cookie.indexOf(sysName) === -1) yield put({ type: 'logout' });
      let currentUser = yield select(state => state.global.currentUser);
      if (
        isEmptyObject(currentUser) &&
        getStorageBykey('currentUser') &&
        !isEmptyObject(JSON.parse(getStorageBykey('currentUser')))
      ) {
        currentUser = JSON.parse(getStorageBykey('currentUser'));
        yield put({
          type: 'save',
          payload: { currentUser },
        });
      } else if (isEmptyObject(currentUser)) {
        yield put({ type: 'logout' });
      }
    },
    *login({ payload }, { call, put }) {
      // const password = sm3(payload.password);
      // payload.password = password.toString().toUpperCase();
      const response = yield call(submit, payload, 'login');
      if (response) {
        const loginInfo = { status: response.success, message: response.message };
        // TODO 权限
        loginInfo.authority = 'user';
        // Login successfully
        if (response.success) {
          loginInfo.currentUser = response.entity || {};
        }
        yield put({
          type: 'changeLoginStatus',
          payload: loginInfo,
        });
        if (response.success) {
          reloadAuthorized();
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          let { redirect } = params;
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
            } else {
              redirect = null;
            }
          }
          // yield put(routerRedux.replace(redirect || '/'));
          window.location.href = redirect || '/';
        }
      }
    },
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          authority: 'guest',
          message: '',
          currentUser: {},
        },
      });
      reloadAuthorized();
      // redirect
      if (window.location.pathname !== '/user/login') {
        yield put(routerRedux.replace('/user/login'));
      }
    },
    // 修改密码
    *updatePassword({ payload }, { call, put }) {
      print(JSON.stringify(payload), api.updatePasswordSubmit.url, 'global');
      const response = yield call(submit, payload, 'updatePassword');
      if (response) {
        if (response.success) {
          showSuccess(api.updatePasswordSubmit, '请重新登录');
          yield put({ type: 'logout' });
        } else {
          showError(api.updatePasswordSubmit, response);
        }
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    changeLoginStatus(state, { payload }) {
      document.cookie = `${sysName}=login;path=/`;
      saveStorage(payload);
      setAuthority(payload.authority);
      return {
        ...state,
        ...payload,
      };
    },
  },

  subscriptions: {
    setup({ history }) {
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      return history.listen(({ pathname, search }) => {
        if (typeof window.ga !== 'undefined') {
          window.ga('send', 'pageview', pathname + search);
        }
      });
    },
  },
};
